﻿using System.Web.Mvc;
using Kratos.Framework.ContentManagement.Models;
using Kratos.Framework.Extensions;
using Kratos.Framework.Filters;
using Kratos.Framework.Modules.Core.Controllers;
using Kratos.Framework.Modules.Core.Services;
using Kratos.Framework.ContentManagement.ViewModels;
using Kratos.Modules.Test.Controllers;
using MvcContrib;

namespace Kratos.Modules.Order.Controllers
{
    public class AccountController : KratosController
    {
        private IUserInfoServices _services;
        public AccountController(IUserInfoServices services)
        {
            _services = services;
        }

        [Ignore]
        public ActionResult LogOn()
        {
            return View();
        }

        [AcceptVerbs(HttpVerbs.Post)]
        [Ignore]
        public ActionResult LogOn(LogModel model)
        {
            if (_services.CanLogOn(model))
            {
                _services.SetAuthenticationCookie(model.UserId);

                if (model.ReturnUrl.NotNullOrEmpty())
                    Redirect(model.ReturnUrl);
            }
            return this.RedirectToAction<HomeController>(a => a.Index());
        }

        [Ignore]
        public ActionResult SignOut()
        {
            _services.SignOut();
            return this.RedirectToAction(c => c.LogOn());
        }

        [Ignore]
        public ActionResult Register()
        {
            return View();
        }

        [AcceptVerbs(HttpVerbs.Post)]
        [UnitOfWork, Ignore]
        public ActionResult Register(UserInfo user)
        {
            if (!_services.IsExistUser(user.UserId))
            {
                user.Password = _services.HashPassword(user.Password);
                _services.Save(user);
                _services.SetAuthenticationCookie(user.UserId);
            }
            return View();
        }

        [AcceptVerbs(HttpVerbs.Post)]
        [Ignore]
        public ActionResult ValidateUser(string userId)
        {
            bool val = _services.IsExistUser(userId);
            return Json(!val);
        }
    }
}
